package com.myapp.config;

import com.gitee.fastmybatis.core.handler.BaseFill;
import com.gitee.fastmybatis.core.handler.FillType;
import com.myapp.entity.UserHobby;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义字段保存类型
 */
public class ListFill extends BaseFill<List<String>> {

    // 作用在哪个class
    private static final Class<?>[] TARGET_CLASS = {
        UserHobby.class
    };

    @Override
    public String getColumnName() {
        return "";
    }

    // 匹配List属性
    @Override
    public boolean match(Class<?> entityClass, Field field, String columnName) {
        return field.getType() == List.class;
    }

    // 读写生效
    @Override
    public FillType getFillType() {
        return FillType.UPDATE;
    }

    @Override
    public Class<?>[] getTargetEntityClasses() {
        return TARGET_CLASS;
    }

    // 数据库值转换到实体类
    @Override
    protected List<String> convertValue(Object columnValue) {
        String value = String.valueOf(columnValue);
        String[] arr = value.split(",");
        return Arrays.stream(arr).collect(Collectors.toList());
    }

    // 保存到数据库
    @Override
    protected Object getFillValue(List<String> defaultValue) {
        return String.join(",", defaultValue);
    }
}